from django.http import HttpResponse
from django.shortcuts import render, redirect,reverse
import pymysql
from dj030201.settings import *
from .myclass.signin import *
from .myclass.shop_cashier import *
from .myclass.manage_model import *
from .myclass.search import *

# Create your views here.
# ==========实例化身份验证对象==========
Login_obj = UserSignin()
# ==========实例化收银模块对象==========
current_customer = Customer()
# ==========实例化管理主界面对象==========
admin_model = manageModel()
# ==========实例化销售查询对象==========
search_modules = search()


def connect_mysql(sql):
    mysql_db = pymysql.connect(host=DB_HOST,user=DB_USER,password=DB_PASSWORD,db=DB_NAME)
    cursor = mysql_db.cursor()
    try:
        cursor.execute(sql)
        results = cursor.fetchall()
    except Exception as e:
        results = '数据库出现异常，具体原因是：' + str(e)
    finally:
        mysql_db.close()
    return results


def index(request):
    return redirect(reverse('login'))


def login(request):
    if request.method == 'GET':
        return render(request,'login.html')

    elif request.method == 'POST':
        Login_obj.loginId = request.POST.get('login')
        Login_obj.loginPwd = request.POST.get('password')
        Login_obj.signin()
        if Login_obj.signin_result == 1:
            return redirect(reverse('cashier') + '?username=' + Login_obj.current_name)
        elif Login_obj.signin_result == 2:
            return redirect(reverse('main') + '?username=' + Login_obj.current_name)
        else:
            msg = Login_obj.error_info
            return render(request,'login.html',context={'result':msg,'login':Login_obj.loginId,'pwd':Login_obj.loginPwd})


def cashier(request):
    if request.method == 'GET':
        username = request.GET.get('username')
        if username:
            while len(current_customer.serialnum) == 0:
                current_customer.get_serialnum()
            current_customer.caculate_total()
            # 所有结果保留两位小数
            current_customer.keep_2()
            return render(request,'cashier.html',context={'username':username,'customer':current_customer})
        else:
            return redirect((reverse('login')))


def main(request):
    username = request.GET.get('username')
    if username:
        admin_model.check_identity(username)
        print('获得身份编号是：{}'.format(admin_model.positionId[0]))
        if admin_model.positionId[0] == 1:
            admin_model.get_models() #module里再次取到值
            admin_model.change_modules()
            modules = admin_model.new_modules
            for module in modules:
                module[2] = reverse(module[2]) + "?username=" + Login_obj.current_name
            print('获得的modules2是：{}'.format(modules))
            return render(request, 'main.html', context={'username': username,'modules':modules})
        else:
            return redirect((reverse('login')))
    else:
        return redirect((reverse('login')))


def sales_query(request):
    if request.method == 'GET':
        username = request.GET.get('username')
        print('拿到用户名了！{}'.format(username))
        search_modules.search_saleslist()
        return render(request,'sales_query.html',context={'username':username,'sales_list':search_modules.saleslist})
    elif request.method == 'POST':
        dt = datetime.now()
        query_dict = {}
        query_dict['serialNum'] = request.POST.get('serialnum')
        query_dict['username'] = request.POST.get('username')
        query_dict['start'] = request.POST.get('start')
        query_dict['end'] = request.POST.get('end')
        if len(query_dict['start']) == 0:
            query_dict['start'] = '%04d-01-01' % (dt.year)
        if len(query_dict['end']) == 0:
            query_dict['end'] = '%04d-%02d-%02d %02d:%02d:%02d' % (dt.year,dt.month,dt.day,dt.hour,dt.minute,dt.second)
        print('查询列表的值是{}'.format(query_dict))
        search_modules.search_lists(query_dict)
        query = search_modules.searchList
        return render(request, 'sales_query.html',context={'username': Login_obj.current_name, 'sales_list': query,'query':query_dict})


def del_sales_query(request):
    serialNumber = request.GET.get('serialNumber')
    search_modules.delete_salesList(serialNumber)
    print('删除成功，流水号为{}'.format(serialNumber))
    return redirect(reverse('sales_query') + '?username=' + Login_obj.current_name)


def salesdetails_query(request):
    username = request.GET.get('username')
    serialNumber = request.GET.get('serialNumber')
    search_modules.search_detailList(serialNumber)
    return render(request,'salesdetail_query.html',context={'username':username,'salesdetail_list':search_modules.detailList,'salesdetailtop_list':search_modules.detailList_top})


def add_product(request):
    barcode = request.GET.get('barcode')
    current_customer.get_product_by_barcode(barcode)
    return redirect(reverse('cashier') + '?username=' + Login_obj.current_name)
    pass


def delete_product(request):
    productId = request.GET.get('productId')
    current_customer.delete_product_to_buylist(productId)
    return redirect(reverse('cashier') + '?username=' + Login_obj.current_name)
    pass


def receive_money(request):
    receive_money = request.GET.get('receive_money')
    current_customer.calculate_return_money(receive_money)
    return redirect(reverse('cashier') + '?username=' + Login_obj.current_name)
    pass


def cashier_cancel(request):
    current_customer.cashier_cancel()
    return redirect(reverse('cashier') + '?username=' + Login_obj.current_name)


def cashier_submit(request):
    current_customer.submit(Login_obj.loginId)
    current_customer.cashier_cancel()
    return redirect(reverse('cashier') + '?username=' + Login_obj.current_name)
    pass
